package com.gary.shiro.service;

import com.gary.shiro.dao.PermissionDAO;
import com.gary.shiro.dao.PermissionRoleDAO;
import com.gary.shiro.po.Permission;
import com.gary.shiro.po.PermissionRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author peng_rui
 * @date 2022/3/26
 */
@Slf4j
@Service
public class PermissionService {
    @Resource
    private PermissionDAO permissionDAO;
    @Resource
    private PermissionRoleDAO permissionRoleDAO;

    public Set<Permission> getPermissionByRoleIds(List<Long> roleIds) {
        Set<Permission> set = new HashSet<>();
        if (CollectionUtils.isEmpty(roleIds)) {
            return set;
        }
        Example example = new Example(PermissionRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("role", roleIds);
        List<PermissionRole> permissionRoles = permissionRoleDAO.selectByExample(example);
        if (CollectionUtils.isEmpty(permissionRoles)) {
            return set;
        }
        List<Long> permissionIds = permissionRoles.stream().map(PermissionRole::getPermissionId).collect(Collectors.toList());

        Example permissionExample = new Example(Permission.class);
        Example.Criteria permissionCriteria = permissionExample.createCriteria();
        permissionCriteria.andIn("id", permissionIds);

        List<Permission> permissions = permissionDAO.selectByExample(permissionExample);
        set = permissions.stream().collect(Collectors.toSet());
        return set;
    }

    public Set<String> queryPathByRoleIds(List<Long> roleIds) {
        Set<String> paths = new HashSet<>();
        if (!CollectionUtils.isEmpty(roleIds)) {
            Set<Permission> permissionSet = getPermissionByRoleIds(roleIds);
            if (!CollectionUtils.isEmpty(permissionSet)) {
                paths = permissionSet.stream().map(Permission::getPath).collect(Collectors.toSet());
            }
        }
        return paths;
    }
}
